package repository

import (
	"context"
	"database/sql"
	"encoding/json"
	"fmt"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/service/forum/model"

	"github.com/sirupsen/logrus"
	"github.com/volatiletech/null/v8"
	"github.com/volatiletech/sqlboiler/v4/boil"
	"github.com/volatiletech/sqlboiler/v4/queries/qm"
	"github.com/zeromicro/go-zero/core/stores/cache"
)

type (
	// PostRepository is an interface to be customized, add more methods here,
	// and implement the added methods in customPostRepository.
	PostRepository interface {
		FindOne(ctx context.Context, id uint64) (*model.ForumPost, error)
		FindOneWithExpire(
			ctx context.Context,
			id uint64,
			expire time.Duration,
		) (*model.ForumPost, error)
		FindOneNoCache(
			ctx context.Context,
			conn boil.ContextExecutor,
			id uint64,
		) (*model.ForumPost, error)
		GetList(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.ForumPost, int64, error) // ##24.12.23##
		Insert(
			ctx context.Context,
			tx boil.ContextExecutor,
			data *model.ForumPost,
			rel *model.ForumPostRel,
		) error // ##24.11.19##
		Update(
			ctx context.Context,
			tx boil.ContextExecutor,
			data *model.ForumPost,
			rel *model.ForumPostRel,
		) error // ##24.11.22##
		UpdateMeta(
			ctx context.Context,
			tx boil.ContextExecutor,
			data *model.ForumPostMetum,
		) (err error)
		UpdateBatch(
			ctx context.Context,
			tx boil.ContextExecutor,
			ids []uint64,
			cols model.M,
			rel *model.ForumPostRel,
		) error
		UpdateMediaBatch(
			ctx context.Context,
			tx boil.ContextExecutor,
			ids []uint64,
			cols model.M,
		) (int64, error)
		UpdateFeedBatch(
			ctx context.Context,
			tx boil.ContextExecutor,
			ids []uint64,
			cols model.M,
		) (int64, error)
		SoftDelete(ctx context.Context, tx boil.ContextExecutor, id uint64) error // ##25.03.25##
		Restore(ctx context.Context, tx boil.ContextExecutor, id uint64) error    // ##24.11.23##

		GetMedia(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.ForumAttachmentRelationship, int64, error) // ##24.12.23##
		GetMeta(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.ForumPostMetum, int64, error) // ##24.12.23##
		GetCard(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.ForumPostCard, int64, error) // ##24.11.19##

		GetMediaCount(
			ctx context.Context,
			filter map[string]map[string][]any, // ##24.12.23##
		) (int64, error)
		GetFeeds(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.ForumFeed, int64, error)
		GetRelationshipList(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.ForumAttachmentRelationship, int64, error) // ##24.11.08##
		InsertMeta(
			ctx context.Context,
			tx boil.ContextExecutor,
			meta []*model.ForumPostMetum,
		) error
	}

	customPostRepository struct {
		modelx.CachedConn
		mysqlConn           *sql.DB
		cacheIdPrefix       string
		cacheIdExpirePrefix string
	}
)

// NewPostRepository returns a repository for the database table.
func NewPostRepository(mysqlConn *sql.DB, cacheConf cache.CacheConf) PostRepository {
	return &customPostRepository{
		CachedConn:          modelx.NewConn(mysqlConn, cacheConf),
		mysqlConn:           mysqlConn,
		cacheIdPrefix:       "cache:forum:posts:id:",
		cacheIdExpirePrefix: "cache:forum:posts:id:expire:",
	}
}

func (r *customPostRepository) FindOne(
	ctx context.Context,
	id uint64,
) (*model.ForumPost, error) {
	cacheIdKey := r.formatPrimary(id)
	var resp model.ForumPost
	err := r.QueryCtx(ctx, &resp, cacheIdKey, func(ctx context.Context, conn *sql.DB, v any) error {
		data, err := model.FindForumPost(ctx, conn, id)
		if err != nil {
			return err
		}

		*v.(*model.ForumPost) = *data
		return nil
	})

	switch err {
	case nil:
		return &resp, nil
	case sql.ErrNoRows:
		return nil, model.ErrNotFound
	default:
		return nil, err
	}
}

func (r *customPostRepository) FindOneWithExpire(
	ctx context.Context,
	id uint64,
	expire time.Duration,
) (*model.ForumPost, error) {
	cacheIdKey := r.formatPrimaryWithExpire(id)
	var resp model.ForumPost
	err := r.QueryWithExpireCtx(ctx, &resp, cacheIdKey, expire, func(ctx context.Context, conn *sql.DB, v any) error {
		data, err := model.FindForumPost(ctx, conn, id)
		if err != nil {
			return err
		}

		*v.(*model.ForumPost) = *data

		return nil
	})

	switch err {
	case nil:
		return &resp, nil
	case sql.ErrNoRows:
		return nil, model.ErrNotFound
	default:
		return nil, err
	}
}

func (r *customPostRepository) FindOneNoCache(
	ctx context.Context,
	conn boil.ContextExecutor,
	id uint64,
) (*model.ForumPost, error) {
	var db boil.ContextExecutor = r.mysqlConn
	if conn != nil {
		db = conn
	}
	data, err := model.FindForumPost(ctx, db, id)
	logrus.Info(fmt.Sprintf("FindOneNoCache err: %+v", err))
	switch err {
	case nil:
		return data, nil
	case sql.ErrNoRows:
		return nil, model.ErrNotFound
	default:
		return nil, err
	}
}

func (r *customPostRepository) GetList(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.ForumPost, count int64, err error) {
	var page int
	var pageSize int
	var limit int
	var selectCol string
	var mods []qm.QueryMod
	var nextCount int64
	var previousCount int64
	var statistic bool
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(uint64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(uint64); ok && val > 0 {
				pageSize = int(val)
			}
		case "limit":
			if val, ok := v.(uint32); ok && val > 0 {
				limit = int(val)
			}
		case "offset":
			if withCount == 2 {
				if val, ok := v.(uint32); ok && val > 0 {
					mods = append(mods, qm.Offset(int(val)))
					previousCount = 1
				}
			}
		case "orderBy":
			if val, ok := v.(string); ok && len(val) > 0 {
				mods = append(mods, qm.OrderBy(val))
			}
		case "preMinId":
			if withCount == 3 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.ForumPostColumns.PostID+" DESC"))
					mods = append(mods, model.ForumPostWhere.PostID.LT(val))
					previousCount = 1
				}
			}
		case "preMaxId":
			if withCount == 4 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.ForumPostColumns.PostID+" ASC"))
					mods = append(mods, model.ForumPostWhere.PostID.GT(val))
					previousCount = 1
				}
			}
		case "select":
			if withCount != 5 {
				if val, ok := v.(string); ok && len(val) > 0 {
					selectCol = val
				}
			}
		case "statistic":
			if val, ok := v.(string); ok && val == "1" { // 按 PostStatus 统计
				statistic = true
			}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.ForumPostColumns.PostID:
			mods = append(mods, modelx.GetIntMods(model.ForumPostColumns.PostID, opMap)...)
		case model.ForumPostColumns.ForumID:
			mods = append(mods, modelx.GetIntMods(model.ForumPostColumns.ForumID, opMap)...)
		case model.ForumPostColumns.TopicID:
			mods = append(mods, modelx.GetIntMods(model.ForumPostColumns.TopicID, opMap)...)
		case model.ForumPostColumns.ParentID:
			mods = append(mods, modelx.GetIntMods(model.ForumPostColumns.ParentID, opMap)...)
		case model.ForumPostColumns.PostAuthorID:
			mods = append(mods, modelx.GetIntMods(model.ForumPostColumns.PostAuthorID, opMap)...)
		case model.ForumPostColumns.PostAuthorNickname:
			mods = append(mods, modelx.GetStringMods(model.ForumPostColumns.PostAuthorNickname, opMap)...)
		case model.ForumPostColumns.PostAuthorEmail:
			mods = append(mods, modelx.GetStringMods(model.ForumPostColumns.PostAuthorEmail, opMap)...)
		case model.ForumPostColumns.PostAuthorIP:
			mods = append(mods, modelx.GetStringMods(model.ForumPostColumns.PostAuthorIP, opMap)...)
		case model.ForumPostColumns.PostAuthorRankID:
			mods = append(mods, modelx.GetIntMods(model.ForumPostColumns.PostAuthorRankID, opMap)...)
		case model.ForumPostColumns.PostAuthorRoleID:
			mods = append(mods, modelx.GetIntMods(model.ForumPostColumns.PostAuthorRoleID, opMap)...)
		case model.ForumPostColumns.PostAuthorAnonymous:
			mods = append(mods, modelx.GetIntMods(model.ForumPostColumns.PostAuthorAnonymous, opMap)...)
		case model.ForumPostColumns.PostTitle:
			mods = append(mods, modelx.GetStringMods(model.ForumPostColumns.PostTitle, opMap)...)
		case model.ForumPostColumns.PostExcerpt:
			mods = append(mods, modelx.GetStringMods(model.ForumPostColumns.PostExcerpt, opMap)...)
		case model.ForumPostColumns.PostStatus:
			mods = append(mods, modelx.GetIntMods(model.ForumPostColumns.PostStatus, opMap)...)
		case model.ForumPostColumns.Sort:
			mods = append(mods, modelx.GetIntMods(model.ForumPostColumns.Sort, opMap)...)
		case model.ForumPostColumns.Sticky:
			mods = append(mods, modelx.GetIntMods(model.ForumPostColumns.Sticky, opMap)...)
		case model.ForumPostColumns.CommentStatus:
			mods = append(mods, modelx.GetIntMods(model.ForumPostColumns.CommentStatus, opMap)...)
		case model.ForumPostColumns.CommentCount:
			mods = append(mods, modelx.GetIntMods(model.ForumPostColumns.CommentCount, opMap)...)
		case model.ForumPostColumns.PhotoCount:
			mods = append(mods, modelx.GetIntMods(model.ForumPostColumns.PhotoCount, opMap)...)
		case model.ForumPostColumns.AverageRating:
			mods = append(mods, modelx.GetStringMods(model.ForumPostColumns.AverageRating, opMap)...)
		case model.ForumPostColumns.PublicDate:
			mods = append(mods, modelx.GetTimeMods(model.ForumPostColumns.PublicDate, opMap)...)
		case model.ForumPostColumns.PostDate:
			mods = append(mods, modelx.GetTimeMods(model.ForumPostColumns.PostDate, opMap)...)
		case model.ForumPostColumns.PostModifiedDate:
			mods = append(mods, modelx.GetTimeMods(model.ForumPostColumns.PostModifiedDate, opMap)...)
		case model.ForumPostColumns.DeletedAt:
			mods = append(mods, modelx.GetTimeMods(model.ForumPostColumns.DeletedAt, opMap)...)
		}
	}

	if statistic {
		mods = append(mods, qm.Select(fmt.Sprintf(
			"%s, count(%s) as %s",
			model.ForumPostColumns.PostStatus,
			model.ForumPostColumns.PostStatus,
			model.ForumPostColumns.Sort,
		)))
		mods = append(mods, qm.GroupBy(model.ForumPostColumns.PostStatus))
		preList, preErr := model.ForumPosts(mods...).All(ctx, r.mysqlConn)
		if preErr != nil {
			err = preErr
			return
		}

		return preList, 0, nil
	}

	if withCount >= 2 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}
	} else if withCount >= 0 {
		count, err = model.ForumPosts(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}
	}

	if pageSize > 0 && (withCount == -1 || withCount == 1) {
		if page > 1 {
			mods = append(mods, qm.Offset(pageSize*(page-1)))
		}
		mods = append(mods, qm.Limit(pageSize))
	}

	var columns []string
	if len(selectCol) > 0 {
		if selectCol == "," {
			columns = append(columns, model.ForumPostColumns.PostID)
		} else {
			columns = strings.Split(selectCol, ",")
		}
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.ForumPosts(mods...).All(ctx, r.mysqlConn)
	if err != nil {
		return
	}

	if withCount >= 2 {
		if limit > 0 && len(list) > limit {
			nextCount = 1
			list = list[:limit]
		}
		count = previousCount + nextCount*2
	}

	return
}

func (r *customPostRepository) Insert(
	ctx context.Context,
	tx boil.ContextExecutor,
	data *model.ForumPost,
	rel *model.ForumPostRel,
) error {
	err := r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		err := data.Insert(ctx, db, boil.Infer())
		if err != nil {
			return err
		}

		if rel == nil {
			return nil
		}

		postId := data.PostID

		if rel.Feed != nil {
			rel.Feed.PostID = postId
			err = rel.Feed.Insert(ctx, db, boil.Infer())
			if err != nil {
				return err
			}
		}

		if len(rel.Meta) > 0 {
			for _, v := range rel.Meta {
				v.PostID = postId
				err = v.Insert(ctx, db, boil.Infer())
				if err != nil {
					return err
				}
			}
		}

		if len(rel.Card) > 0 {
			for _, v := range rel.Card {
				v.PostID = postId
				err = v.Insert(ctx, db, boil.Infer())
				if err != nil {
					return err
				}
			}
		}

		if len(rel.Media) > 0 {
			for _, v := range rel.Media {
				v.ObjectID = postId
				v.ObjectType = uint16(globalkey.AttachmentLogTypeForumPost)
				err = v.Insert(ctx, db, boil.Infer())
				if err != nil {
					return err
				}
			}
		}

		if len(rel.TagIds) > 0 {
			for _, tid := range rel.TagIds {
				var relationShip model.ForumTermRelationship
				relationShip.ObjectID = postId
				relationShip.ObjectType = uint16(globalkey.AttachmentLogTypeForumPost)
				relationShip.TermID = tid
				err = relationShip.Insert(ctx, db, boil.Infer())
				if err != nil {
					return err
				}
			}
		}

		if len(rel.Term) > 0 {
			for _, v := range rel.Term {
				v.ObjectID = postId
				err = v.Insert(ctx, db, boil.Infer())
				if err != nil {
					return err
				}
			}
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customPostRepository) InsertMeta(
	ctx context.Context,
	tx boil.ContextExecutor,
	meta []*model.ForumPostMetum,
) error {
	err := r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}
		if len(meta) > 0 {
			for _, v := range meta {
				err := v.Insert(ctx, db, boil.Infer())
				if err != nil {
					return err
				}
			}
		}
		return nil
	})
	return err
}

func (r *customPostRepository) Update(
	ctx context.Context,
	tx boil.ContextExecutor,
	data *model.ForumPost,
	rel *model.ForumPostRel,
) error {
	err := r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		blacklist := []string{
			model.ForumPostColumns.PostID,
			model.ForumPostColumns.ForumID,
			model.ForumPostColumns.PostAuthorID,
			model.ForumPostColumns.PostDate,
			model.ForumPostColumns.DeletedAt,
		}
		if rel != nil && len(rel.Blacklist) > 0 {
			blacklist = append(blacklist, rel.Blacklist...)
		}
		rowsAff, err := data.Update(ctx, db, boil.Blacklist(blacklist...))
		if err != nil {
			return err
		}

		if rowsAff == 0 {
			return model.ErrNotUpdated
		}

		if rel == nil {
			return nil
		}

		postId := data.PostID
		if len(rel.Meta) > 0 {
			for _, v := range rel.Meta {
				if v.MetaID > 0 {
					_, err = v.Update(ctx, db, boil.Blacklist(
						model.ForumPostMetumColumns.MetaID,
						model.ForumPostMetumColumns.PostID,
						model.ForumPostMetumColumns.MetaKey,
					))
					if err != nil {
						return err
					}
				} else {
					v.PostID = postId
					err = v.Insert(ctx, db, boil.Infer())
					if err != nil {
						return err
					}
				}
			}
		}

		if len(rel.Media) > 0 {
			for _, v := range rel.Media {
				if v.AttachmentRelationshipID > 0 {
					_, err = v.Update(ctx, db, boil.Blacklist(
						model.ForumAttachmentRelationshipColumns.AttachmentRelationshipID,
						model.ForumAttachmentRelationshipColumns.ObjectID,
						model.ForumAttachmentRelationshipColumns.ObjectType,
					))
					if err != nil {
						return err
					}
				} else {
					v.ObjectID = postId
					v.ObjectType = uint16(globalkey.AttachmentLogTypeForumPost)
					err = v.Insert(ctx, db, boil.Infer())
					if err != nil {
						return err
					}
				}
			}
		}

		if len(rel.Card) > 0 {
			for _, v := range rel.Card {
				if v.ID > 0 {
					_, err = v.Update(ctx, db, boil.Blacklist(
						model.ForumPostCardColumns.ID,
						model.ForumPostCardColumns.PostID,
						model.ForumPostCardColumns.ObjectID,
						model.ForumPostCardColumns.ObjectType,
					))
					if err != nil {
						return err
					}
				} else {
					v.PostID = postId
					err = v.Insert(ctx, db, boil.Infer())
					if err != nil {
						return err
					}
				}
			}
		}

		if len(rel.TagIds) > 0 {
			for _, tid := range rel.TagIds {
				var relationShip model.ForumTermRelationship
				relationShip.ObjectID = postId
				relationShip.ObjectType = uint16(globalkey.AttachmentLogTypeForumPost)
				relationShip.TermID = tid
				err = relationShip.Insert(ctx, db, boil.Infer())
				if err != nil {
					return err
				}
			}
		}

		if len(rel.Term) > 0 {
			for _, v := range rel.Term {
				v.ObjectID = postId
				err = v.Insert(ctx, db, boil.Infer())
				if err != nil {
					return err
				}
			}
		}

		if len(rel.Term) > 0 {
			for _, v := range rel.Term {
				if v.RelationshipID > 0 {
					_, err = v.Update(ctx, db, boil.Blacklist(
						model.ForumTermRelationshipColumns.RelationshipID,
						model.ForumTermRelationshipColumns.ObjectID,
						model.ForumTermRelationshipColumns.ObjectType,
						model.ForumTermRelationshipColumns.TermID,
					))
					if err != nil {
						return err
					}
				} else {
					v.ObjectID = postId
					err = v.Insert(ctx, db, boil.Infer())
					if err != nil {
						return err
					}
				}
			}
		}

		if len(rel.DelMetaIds) > 0 {
			var mods []qm.QueryMod
			mods = append(mods, model.ForumPostMetumWhere.MetaID.IN(rel.DelMetaIds))
			_, err = model.ForumPostMeta(mods...).DeleteAll(ctx, db)
			if err != nil {
				return err
			}
		}

		if len(rel.DelMediaIds) > 0 {
			var mods []qm.QueryMod
			mods = append(mods, model.ForumAttachmentRelationshipWhere.AttachmentRelationshipID.IN(rel.DelMediaIds))
			_, err = model.ForumAttachmentRelationships(mods...).DeleteAll(ctx, db)
			if err != nil {
				return err
			}
		}

		if len(rel.DelCardIds) > 0 {
			var mods []qm.QueryMod
			mods = append(mods, model.ForumPostCardWhere.ID.IN(rel.DelCardIds))
			_, err = model.ForumPostCards(mods...).DeleteAll(ctx, db)
			if err != nil {
				return err
			}
		}

		if len(rel.DelTermIds) > 0 {
			var mods []qm.QueryMod
			mods = append(mods, model.ForumTermRelationshipWhere.RelationshipID.IN(rel.DelTermIds))
			_, err = model.ForumTermRelationships(mods...).DeleteAll(ctx, db)
			if err != nil {
				return err
			}
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customPostRepository) UpdateBatch(
	ctx context.Context,
	tx boil.ContextExecutor,
	ids []uint64,
	cols model.M,
	rel *model.ForumPostRel,
) error {
	if len(ids) > 0 {
		err := r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
			var db boil.ContextExecutor
			if tx != nil {
				db = tx
			} else {
				db = conn
			}

			var mods []qm.QueryMod
			mods = append(mods, model.ForumPostWhere.PostID.IN(ids))

			rowsAff, err := model.ForumPosts(mods...).UpdateAll(ctx, db, cols)
			if err != nil {
				return err
			}

			if rowsAff == 0 {
				return model.ErrNotUpdated
			}

			if len(rel.Logs) > 0 {
				for _, v := range rel.Logs {
					err = v.Insert(ctx, db, boil.Infer())
					if err != nil {
						return err
					}
				}
			}

			if len(rel.Notices) > 0 {
				for _, v := range rel.Notices {
					err = v.Insert(ctx, db, boil.Infer())
					if err != nil {
						return err
					}
				}
			}

			return nil
		}, r.formatPrimaries(ids)...)

		return err
	}

	return nil
}

func (r *customPostRepository) UpdateMediaBatch(
	ctx context.Context,
	tx boil.ContextExecutor,
	ids []uint64,
	cols model.M,
) (rowsAff int64, err error) {
	if len(ids) > 0 {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = r.mysqlConn
		}

		var mods []qm.QueryMod
		mods = append(mods, model.ForumAttachmentRelationshipWhere.AttachmentRelationshipID.IN(ids))
		rowsAff, err = model.ForumAttachmentRelationships(mods...).UpdateAll(ctx, db, cols)
	}

	return
}

func (r *customPostRepository) UpdateMeta(
	ctx context.Context,
	tx boil.ContextExecutor,
	data *model.ForumPostMetum,
) (err error) {
	err = r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		rowsAff, err := data.Update(ctx, db, boil.Blacklist(
			model.ForumPostMetumColumns.PostID,
			model.ForumPostMetumColumns.MetaKey,
		))
		if err != nil {
			return err
		}

		if rowsAff == 0 {
			return model.ErrNotUpdated
		}
		return nil
	}, r.getCacheKeys(&model.ForumPost{PostID: data.PostID})...)

	return nil
}

func (r *customPostRepository) UpdateFeedBatch(
	ctx context.Context,
	tx boil.ContextExecutor,
	ids []uint64,
	cols model.M,
) (rowsAff int64, err error) {
	if len(ids) > 0 {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = r.mysqlConn
		}

		var mods []qm.QueryMod
		mods = append(mods, model.ForumFeedWhere.ID.IN(ids))
		rowsAff, err = model.ForumFeeds(mods...).UpdateAll(ctx, db, cols)
	}

	return
}

func (r *customPostRepository) SoftDelete(
	ctx context.Context,
	tx boil.ContextExecutor,
	id uint64,
) error {
	data, err := r.FindOneNoCache(ctx, tx, id)
	if err != nil {
		if err == model.ErrNotFound {
			return nil
		}

		return err
	}

	if data.PostStatus == uint8(globalkey.StatusDeleted) {
		return nil
	}

	data.DelStatus = data.PostStatus
	data.PostStatus = uint8(globalkey.StatusDeleted)
	data.DeletedAt = null.TimeFrom(time.Now())

	err = r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		rowsAff, err := data.Update(ctx, db, boil.Whitelist(
			model.ForumPostColumns.DelStatus,
			model.ForumPostColumns.PostStatus,
			model.ForumPostColumns.DeletedAt,
		))
		if err != nil {
			return err
		}

		if rowsAff == 0 {
			return model.ErrNotUpdated
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customPostRepository) Restore(
	ctx context.Context,
	tx boil.ContextExecutor,
	id uint64,
) error {
	data, err := r.FindOneNoCache(ctx, tx, id)
	if err != nil {
		if err == model.ErrNotFound {
			return nil
		}

		return err
	}

	if data.PostStatus != uint8(globalkey.StatusDeleted) {
		return nil
	}

	data.PostStatus = data.DelStatus
	data.DeletedAt = null.TimeFromPtr(nil)

	err = r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		rowsAff, err := data.Update(ctx, db, boil.Whitelist(
			model.ForumPostColumns.PostStatus,
			model.ForumPostColumns.DeletedAt,
		))
		if err != nil {
			return err
		}

		if rowsAff == 0 {
			return model.ErrNotUpdated
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customPostRepository) getCacheKeys(data *model.ForumPost) []string {
	if data == nil {
		return []string{}
	}

	cacheIdKey := r.formatPrimary(data.PostID)
	cacheIdExpireKey := r.formatPrimaryWithExpire(data.PostID)
	cacheKeys := []string{
		cacheIdKey,
		cacheIdExpireKey,
	}

	return cacheKeys
}

func (r *customPostRepository) formatPrimary(primary any) string {
	return fmt.Sprintf("%s%v", r.cacheIdPrefix, primary)
}

func (r *customPostRepository) formatPrimaryWithExpire(primary any) string {
	return fmt.Sprintf("%s%v", r.cacheIdExpirePrefix, primary)
}

func (r *customPostRepository) formatPrimaries(primaries []uint64) []string {
	var resp []string
	for _, primary := range primaries {
		resp = append(resp, r.formatPrimary(primary))
		resp = append(resp, r.formatPrimaryWithExpire(primary))
	}

	return resp
}

func (r *customPostRepository) queryPrimary(ctx context.Context, conn *sql.DB, v, primary any) error {
	var pid uint64
	if jsonId, ok := primary.(json.Number); ok {
		if int64Id, err := jsonId.Int64(); err == nil {
			pid = uint64(int64Id)
		} else {
			return err
		}
	}

	data, err := model.FindForumPost(ctx, conn, pid)
	if err != nil {
		return err
	}

	*v.(*model.ForumPost) = *data

	return nil
}

func (r *customPostRepository) GetMediaCount(
	ctx context.Context,
	filter map[string]map[string][]any,
) (count int64, err error) {
	var mods []qm.QueryMod
	for key, opMap := range filter {
		switch key {
		case model.ForumPostColumns.PostID:
			mods = append(mods, modelx.GetIntMods(model.ForumPostColumns.PostID, opMap)...)
		case model.ForumPostColumns.ForumID:
			mods = append(mods, modelx.GetIntMods(model.ForumPostColumns.ForumID, opMap)...)
		case model.ForumPostColumns.TopicID:
			mods = append(mods, modelx.GetIntMods(model.ForumPostColumns.TopicID, opMap)...)
		case model.ForumPostColumns.ParentID:
			mods = append(mods, modelx.GetIntMods(model.ForumPostColumns.ParentID, opMap)...)
		case model.ForumPostColumns.PostAuthorID:
			mods = append(mods, modelx.GetIntMods(model.ForumPostColumns.PostAuthorID, opMap)...)
		case model.ForumPostColumns.PostAuthorNickname:
			mods = append(mods, modelx.GetStringMods(model.ForumPostColumns.PostAuthorNickname, opMap)...)
		case model.ForumPostColumns.PostAuthorEmail:
			mods = append(mods, modelx.GetStringMods(model.ForumPostColumns.PostAuthorEmail, opMap)...)
		case model.ForumPostColumns.PostAuthorIP:
			mods = append(mods, modelx.GetStringMods(model.ForumPostColumns.PostAuthorIP, opMap)...)
		case model.ForumPostColumns.PostAuthorRankID:
			mods = append(mods, modelx.GetIntMods(model.ForumPostColumns.PostAuthorRankID, opMap)...)
		case model.ForumPostColumns.PostAuthorRoleID:
			mods = append(mods, modelx.GetIntMods(model.ForumPostColumns.PostAuthorRoleID, opMap)...)
		case model.ForumPostColumns.PostAuthorAnonymous:
			mods = append(mods, modelx.GetIntMods(model.ForumPostColumns.PostAuthorAnonymous, opMap)...)
		case model.ForumPostColumns.PostTitle:
			mods = append(mods, modelx.GetStringMods(model.ForumPostColumns.PostTitle, opMap)...)
		case model.ForumPostColumns.PostExcerpt:
			mods = append(mods, modelx.GetStringMods(model.ForumPostColumns.PostExcerpt, opMap)...)
		case model.ForumPostColumns.PostStatus:
			mods = append(mods, modelx.GetIntMods(model.ForumPostColumns.PostStatus, opMap)...)
		case model.ForumPostColumns.Sort:
			mods = append(mods, modelx.GetIntMods(model.ForumPostColumns.Sort, opMap)...)
		case model.ForumPostColumns.Sticky:
			mods = append(mods, modelx.GetIntMods(model.ForumPostColumns.Sticky, opMap)...)
		case model.ForumPostColumns.CommentStatus:
			mods = append(mods, modelx.GetIntMods(model.ForumPostColumns.CommentStatus, opMap)...)
		case model.ForumPostColumns.CommentCount:
			mods = append(mods, modelx.GetIntMods(model.ForumPostColumns.CommentCount, opMap)...)
		case model.ForumPostColumns.PhotoCount:
			mods = append(mods, modelx.GetIntMods(model.ForumPostColumns.PhotoCount, opMap)...)
		case model.ForumPostColumns.AverageRating:
			mods = append(mods, modelx.GetStringMods(model.ForumPostColumns.AverageRating, opMap)...)
		case model.ForumPostColumns.PublicDate:
			mods = append(mods, modelx.GetTimeMods(model.ForumPostColumns.PublicDate, opMap)...)
		case model.ForumPostColumns.PostDate:
			mods = append(mods, modelx.GetTimeMods(model.ForumPostColumns.PostDate, opMap)...)
		case model.ForumPostColumns.PostModifiedDate:
			mods = append(mods, modelx.GetTimeMods(model.ForumPostColumns.PostModifiedDate, opMap)...)
		case model.ForumPostColumns.DeletedAt:
			mods = append(mods, modelx.GetTimeMods(model.ForumPostColumns.DeletedAt, opMap)...)
		}
	}

	mods = append(mods, qm.Select(fmt.Sprintf("sum(%s) as photo_count_sum", model.ForumPostColumns.PhotoCount)))
	mods = append(mods, qm.From(model.TableNames.ForumPosts+" as posts"))

	var info RandomInfo
	// Use query building
	err = model.NewQuery(mods...).Bind(ctx, r.mysqlConn, &info)
	if err != nil {
		return
	}

	return int64(info.PhotoCount), nil
}

func (r *customPostRepository) GetMedia(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.ForumAttachmentRelationship, count int64, err error) {
	var page int
	var pageSize int
	var limit int
	var selectCol string
	var mods []qm.QueryMod
	var nextCount int64
	var previousCount int64
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(uint64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(uint64); ok && val > 0 {
				pageSize = int(val)
			}
		case "limit":
			if val, ok := v.(uint32); ok && val > 0 {
				limit = int(val)
			}
		case "offset":
			if withCount == 2 {
				if val, ok := v.(uint32); ok && val > 0 {
					mods = append(mods, qm.Offset(int(val)))
					previousCount = 1
				}
			}
		case "orderBy":
			if val, ok := v.(string); ok && len(val) > 0 {
				mods = append(mods, qm.OrderBy(val))
			}
		case "preMinId":
			if withCount == 3 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.ForumAttachmentRelationshipColumns.AttachmentRelationshipID+" DESC"))
					mods = append(mods, model.ForumAttachmentRelationshipWhere.AttachmentRelationshipID.LT(val))
					previousCount = 1
				}
			}
		case "preMaxId":
			if withCount == 4 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.ForumAttachmentRelationshipColumns.AttachmentRelationshipID+" ASC"))
					mods = append(mods, model.ForumAttachmentRelationshipWhere.AttachmentRelationshipID.GT(val))
					previousCount = 1
				}
			}
		case "select":
			if withCount != 5 {
				if val, ok := v.(string); ok && len(val) > 0 {
					selectCol = val
				}
			}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.ForumAttachmentRelationshipColumns.AttachmentRelationshipID:
			mods = append(mods, modelx.GetIntMods(model.ForumAttachmentRelationshipColumns.AttachmentRelationshipID, opMap)...)
		case model.ForumAttachmentRelationshipColumns.ObjectID:
			mods = append(mods, modelx.GetIntMods(model.ForumAttachmentRelationshipColumns.ObjectID, opMap)...)
		case model.ForumAttachmentRelationshipColumns.ObjectType:
			mods = append(mods, modelx.GetIntMods(model.ForumAttachmentRelationshipColumns.ObjectType, opMap)...)
		case model.ForumAttachmentRelationshipColumns.AttachmentID:
			mods = append(mods, modelx.GetIntMods(model.ForumAttachmentRelationshipColumns.AttachmentID, opMap)...)
		case model.ForumAttachmentRelationshipColumns.AttachmentThumbnail:
			mods = append(mods, modelx.GetIntMods(model.ForumAttachmentRelationshipColumns.AttachmentThumbnail, opMap)...)
		case model.ForumAttachmentRelationshipColumns.AttachmentOrder:
			mods = append(mods, modelx.GetIntMods(model.ForumAttachmentRelationshipColumns.AttachmentOrder, opMap)...)
		case model.ForumAttachmentRelationshipColumns.AttachmentSource:
			mods = append(mods, modelx.GetStringMods(model.ForumAttachmentRelationshipColumns.AttachmentSource, opMap)...)
		case model.ForumAttachmentRelationshipColumns.AttachmentImageURL:
			mods = append(mods, modelx.GetStringMods(model.ForumAttachmentRelationshipColumns.AttachmentImageURL, opMap)...)
		case model.ForumAttachmentRelationshipColumns.AttachmentImageAlt:
			mods = append(mods, modelx.GetStringMods(model.ForumAttachmentRelationshipColumns.AttachmentImageAlt, opMap)...)
		}
	}

	if withCount >= 2 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}
	} else if withCount >= 0 {
		count, err = model.ForumAttachmentRelationships(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}
	}

	if pageSize > 0 && (withCount == -1 || withCount == 1) {
		if page > 1 {
			mods = append(mods, qm.Offset(pageSize*(page-1)))
		}
		mods = append(mods, qm.Limit(pageSize))
	}

	var columns []string
	if len(selectCol) > 0 {
		if selectCol == "," {
			columns = append(columns, model.ForumAttachmentRelationshipColumns.AttachmentRelationshipID)
		} else {
			columns = strings.Split(selectCol, ",")
		}
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.ForumAttachmentRelationships(mods...).All(ctx, r.mysqlConn)
	if err != nil {
		return
	}

	if withCount >= 2 {
		if limit > 0 && len(list) > limit {
			nextCount = 1
			list = list[:limit]
		}
		count = previousCount + nextCount*2
	}

	return
}

func (r *customPostRepository) GetMeta(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.ForumPostMetum, count int64, err error) {
	var page int
	var pageSize int
	var limit int
	var selectCol string
	var mods []qm.QueryMod
	var nextCount int64
	var previousCount int64
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(uint64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(uint64); ok && val > 0 {
				pageSize = int(val)
			}
		case "limit":
			if val, ok := v.(uint32); ok && val > 0 {
				limit = int(val)
			}
		case "offset":
			if withCount == 2 {
				if val, ok := v.(uint32); ok && val > 0 {
					mods = append(mods, qm.Offset(int(val)))
					previousCount = 1
				}
			}
		case "orderBy":
			if val, ok := v.(string); ok && len(val) > 0 {
				mods = append(mods, qm.OrderBy(val))
			}
		case "preMinId":
			if withCount == 3 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.ForumPostMetumColumns.MetaID+" DESC"))
					mods = append(mods, model.ForumPostMetumWhere.MetaID.LT(val))
					previousCount = 1
				}
			}
		case "preMaxId":
			if withCount == 4 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.ForumPostMetumColumns.MetaID+" ASC"))
					mods = append(mods, model.ForumPostMetumWhere.MetaID.GT(val))
					previousCount = 1
				}
			}
		case "select":
			if withCount != 5 {
				if val, ok := v.(string); ok && len(val) > 0 {
					selectCol = val
				}
			}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.ForumPostMetumColumns.MetaID:
			mods = append(mods, modelx.GetIntMods(model.ForumPostMetumColumns.MetaID, opMap)...)
		case model.ForumPostMetumColumns.PostID:
			mods = append(mods, modelx.GetIntMods(model.ForumPostMetumColumns.PostID, opMap)...)
		case model.ForumPostMetumColumns.MetaKey:
			mods = append(mods, modelx.GetStringMods(model.ForumPostMetumColumns.MetaKey, opMap)...)
		case model.ForumPostMetumColumns.MetaValue:
			mods = append(mods, modelx.GetStringMods(model.ForumPostMetumColumns.MetaValue, opMap)...)
		}
	}

	if withCount >= 2 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}
	} else if withCount >= 0 {
		count, err = model.ForumPostMeta(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}
	}

	if pageSize > 0 && (withCount == -1 || withCount == 1) {
		if page > 1 {
			mods = append(mods, qm.Offset(pageSize*(page-1)))
		}
		mods = append(mods, qm.Limit(pageSize))
	}

	var columns []string
	if len(selectCol) > 0 {
		if selectCol == "," {
			columns = append(columns, model.ForumPostMetumColumns.MetaID)
		} else {
			columns = strings.Split(selectCol, ",")
		}
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.ForumPostMeta(mods...).All(ctx, r.mysqlConn)
	if err != nil {
		return
	}

	if withCount >= 2 {
		if limit > 0 && len(list) > limit {
			nextCount = 1
			list = list[:limit]
		}
		count = previousCount + nextCount*2
	}

	return
}

func (r *customPostRepository) GetCard(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.ForumPostCard, count int64, err error) {
	var page int
	var pageSize int
	var limit int
	var selectCol string
	var mods []qm.QueryMod
	var nextCount int64
	var previousCount int64
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(uint64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(uint64); ok && val > 0 {
				pageSize = int(val)
			}
		case "limit":
			if val, ok := v.(uint32); ok && val > 0 {
				limit = int(val)
			}
		case "offset":
			if withCount == 2 {
				if val, ok := v.(uint32); ok && val > 0 {
					mods = append(mods, qm.Offset(int(val)))
					previousCount = 1
				}
			}
		case "orderBy":
			if val, ok := v.(string); ok && len(val) > 0 {
				mods = append(mods, qm.OrderBy(val))
			}
		case "preMinId":
			if withCount == 3 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.ForumPostCardColumns.ID+" DESC"))
					mods = append(mods, model.ForumPostCardWhere.ID.LT(val))
					previousCount = 1
				}
			}
		case "preMaxId":
			if withCount == 4 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.ForumPostCardColumns.ID+" ASC"))
					mods = append(mods, model.ForumPostCardWhere.ID.GT(val))
					previousCount = 1
				}
			}
		case "select":
			if withCount != 5 {
				if val, ok := v.(string); ok && len(val) > 0 {
					selectCol = val
				}
			}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.ForumPostCardColumns.ID:
			mods = append(mods, modelx.GetIntMods(model.ForumPostCardColumns.ID, opMap)...)
		case model.ForumPostCardColumns.PostID:
			mods = append(mods, modelx.GetIntMods(model.ForumPostCardColumns.PostID, opMap)...)
		case model.ForumPostCardColumns.ObjectID:
			mods = append(mods, modelx.GetIntMods(model.ForumPostCardColumns.ObjectID, opMap)...)
		case model.ForumPostCardColumns.ObjectType:
			mods = append(mods, modelx.GetIntMods(model.ForumPostCardColumns.ObjectType, opMap)...)
		case model.ForumPostCardColumns.LinkURL:
			mods = append(mods, modelx.GetStringMods(model.ForumPostCardColumns.LinkURL, opMap)...)
		case model.ForumPostCardColumns.Title:
			mods = append(mods, modelx.GetStringMods(model.ForumPostCardColumns.Title, opMap)...)
		case model.ForumPostCardColumns.Subtitle:
			mods = append(mods, modelx.GetStringMods(model.ForumPostCardColumns.Subtitle, opMap)...)
		case model.ForumPostCardColumns.Label:
			mods = append(mods, modelx.GetStringMods(model.ForumPostCardColumns.Label, opMap)...)
		case model.ForumPostCardColumns.Price:
			mods = append(mods, modelx.GetStringMods(model.ForumPostCardColumns.Price, opMap)...)
		}
	}

	if withCount >= 2 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}
	} else if withCount >= 0 {
		count, err = model.ForumPostCards(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}
	}

	if pageSize > 0 && (withCount == -1 || withCount == 1) {
		if page > 1 {
			mods = append(mods, qm.Offset(pageSize*(page-1)))
		}
		mods = append(mods, qm.Limit(pageSize))
	}

	var columns []string
	if len(selectCol) > 0 {
		if selectCol == "," {
			columns = append(columns, model.ForumPostCardColumns.ID)
		} else {
			columns = strings.Split(selectCol, ",")
		}
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.ForumPostCards(mods...).All(ctx, r.mysqlConn)
	if err != nil {
		return
	}

	if withCount >= 2 {
		if limit > 0 && len(list) > limit {
			nextCount = 1
			list = list[:limit]
		}
		count = previousCount + nextCount*2
	}

	return
}

func (r *customPostRepository) GetFeeds(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.ForumFeed, count int64, err error) {
	var page int
	var pageSize int
	var limit int
	var selectCol string
	var mods []qm.QueryMod
	var nextCount int64
	var previousCount int64
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(uint64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(uint64); ok && val > 0 {
				pageSize = int(val)
			}
		case "limit":
			if val, ok := v.(uint32); ok && val > 0 {
				limit = int(val)
			}
		case "offset":
			if withCount == 2 {
				if val, ok := v.(uint32); ok && val > 0 {
					mods = append(mods, qm.Offset(int(val)))
					previousCount = 1
				}
			}
		case "preMinId":
			if withCount == 3 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.ForumFeedColumns.ID+" DESC"))
					mods = append(mods, model.ForumFeedWhere.ID.LT(val))
					previousCount = 1
				}
			}
		case "preMaxId":
			if withCount == 4 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.ForumFeedColumns.ID+" ASC"))
					mods = append(mods, model.ForumFeedWhere.ID.GT(val))
					previousCount = 1
				}
			}
		case "orderBy":
			if withCount != 3 && withCount != 4 {
				if val, ok := v.(string); ok && val != "" {
					mods = append(mods, qm.OrderBy(val))
				}
			}
		case "select":
			if withCount != 5 {
				if val, ok := v.(string); ok && val != "" {
					selectCol = val
				}
			}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.ForumFeedColumns.ID:
			mods = append(mods, modelx.GetIntMods(model.ForumFeedColumns.ID, opMap)...)
		case model.ForumFeedColumns.UserID:
			mods = append(mods, modelx.GetIntMods(model.ForumFeedColumns.UserID, opMap)...)
		case model.ForumFeedColumns.ForumID:
			mods = append(mods, modelx.GetIntMods(model.ForumFeedColumns.ForumID, opMap)...)
		case model.ForumFeedColumns.TopicID:
			mods = append(mods, modelx.GetIntMods(model.ForumFeedColumns.TopicID, opMap)...)
		case model.ForumFeedColumns.PostID:
			mods = append(mods, modelx.GetIntMods(model.ForumFeedColumns.PostID, opMap)...)
		case model.ForumFeedColumns.AuthorID:
			mods = append(mods, modelx.GetIntMods(model.ForumFeedColumns.AuthorID, opMap)...)
		case model.ForumFeedColumns.AuthorNickname:
			mods = append(mods, modelx.GetStringMods(model.ForumFeedColumns.AuthorNickname, opMap)...)
		case model.ForumFeedColumns.AuthorRankID:
			mods = append(mods, modelx.GetIntMods(model.ForumFeedColumns.AuthorRankID, opMap)...)
		case model.ForumFeedColumns.AuthorRoleID:
			mods = append(mods, modelx.GetIntMods(model.ForumFeedColumns.AuthorRoleID, opMap)...)
		case model.ForumFeedColumns.AuthorAnonymous:
			mods = append(mods, modelx.GetIntMods(model.ForumFeedColumns.AuthorAnonymous, opMap)...)
		case model.ForumFeedColumns.Status:
			mods = append(mods, modelx.GetIntMods(model.ForumFeedColumns.Status, opMap)...)
		case model.ForumFeedColumns.Sticky:
			mods = append(mods, modelx.GetIntMods(model.ForumFeedColumns.Sticky, opMap)...)
		case model.ForumFeedColumns.LikeCount:
			mods = append(mods, modelx.GetIntMods(model.ForumFeedColumns.LikeCount, opMap)...)
		case model.ForumFeedColumns.ReplyCount:
			mods = append(mods, modelx.GetIntMods(model.ForumFeedColumns.ReplyCount, opMap)...)
		}
	}

	if withCount >= 2 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}
	} else if withCount >= 0 {
		count, err = model.ForumFeeds(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}

		if pageSize > 0 {
			if page > 1 {
				mods = append(mods, qm.Offset(pageSize*(page-1)))
			}
			mods = append(mods, qm.Limit(pageSize))
		}
	} else {
		if pageSize > 0 {
			if page > 1 {
				mods = append(mods, qm.Offset(pageSize*(page-1)))
			}
			mods = append(mods, qm.Limit(pageSize))
		}
	}

	var columns []string
	if selectCol != "" {
		if selectCol != "," {
			columns = strings.Split(selectCol, ",")
		} else {
			columns = append(columns, model.ForumFeedColumns.ID)
		}
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.ForumFeeds(mods...).All(ctx, r.mysqlConn)
	if withCount >= 2 {
		if limit > 0 && len(list) > limit {
			nextCount = 1
			list = list[:limit]
		}
		count = previousCount + nextCount*2
	}

	return
}

func (r *customPostRepository) GetRelationshipList(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.ForumAttachmentRelationship, count int64, err error) {
	var page int
	var pageSize int
	var limit int
	var selectCol string
	var mods []qm.QueryMod
	var nextCount int64
	var previousCount int64
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(uint64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(uint64); ok && val > 0 {
				pageSize = int(val)
			}
		case "limit":
			if val, ok := v.(uint32); ok && val > 0 {
				limit = int(val)
			}
		case "offset":
			if withCount == 2 {
				if val, ok := v.(uint32); ok && val > 0 {
					mods = append(mods, qm.Offset(int(val)))
					previousCount = 1
				}
			}
		case "orderBy":
			if val, ok := v.(string); ok && len(val) > 0 {
				mods = append(mods, qm.OrderBy(val))
			}
		case "preMinId":
			if withCount == 3 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.ForumAttachmentRelationshipColumns.AttachmentRelationshipID+" DESC"))
					mods = append(mods, model.ForumAttachmentRelationshipWhere.AttachmentRelationshipID.LT(val))
					previousCount = 1
				}
			}
		case "preMaxId":
			if withCount == 4 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.ForumAttachmentRelationshipColumns.AttachmentRelationshipID+" ASC"))
					mods = append(mods, model.ForumAttachmentRelationshipWhere.AttachmentRelationshipID.GT(val))
					previousCount = 1
				}
			}
		case "select":
			if withCount != 5 {
				if val, ok := v.(string); ok && len(val) > 0 {
					selectCol = val
				}
			}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.ForumAttachmentRelationshipColumns.AttachmentRelationshipID:
			mods = append(mods, modelx.GetIntMods(model.ForumAttachmentRelationshipColumns.AttachmentRelationshipID, opMap)...)
		case model.ForumAttachmentRelationshipColumns.ObjectID:
			mods = append(mods, modelx.GetIntMods(model.ForumAttachmentRelationshipColumns.ObjectID, opMap)...)
		case model.ForumAttachmentRelationshipColumns.ObjectType:
			mods = append(mods, modelx.GetIntMods(model.ForumAttachmentRelationshipColumns.ObjectType, opMap)...)
		case model.ForumAttachmentRelationshipColumns.AttachmentID:
			mods = append(mods, modelx.GetIntMods(model.ForumAttachmentRelationshipColumns.AttachmentID, opMap)...)
		case model.ForumAttachmentRelationshipColumns.AttachmentThumbnail:
			mods = append(mods, modelx.GetIntMods(model.ForumAttachmentRelationshipColumns.AttachmentThumbnail, opMap)...)
		case model.ForumAttachmentRelationshipColumns.AttachmentOrder:
			mods = append(mods, modelx.GetIntMods(model.ForumAttachmentRelationshipColumns.AttachmentOrder, opMap)...)
		case model.ForumAttachmentRelationshipColumns.AttachmentSource:
			mods = append(mods, modelx.GetStringMods(model.ForumAttachmentRelationshipColumns.AttachmentSource, opMap)...)
		case model.ForumAttachmentRelationshipColumns.AttachmentImageURL:
			mods = append(mods, modelx.GetStringMods(model.ForumAttachmentRelationshipColumns.AttachmentImageURL, opMap)...)
		case model.ForumAttachmentRelationshipColumns.AttachmentImageAlt:
			mods = append(mods, modelx.GetStringMods(model.ForumAttachmentRelationshipColumns.AttachmentImageAlt, opMap)...)
		case model.ForumAttachmentRelationshipColumns.AttachmentImageMeta:
			mods = append(mods, modelx.GetStringMods(model.ForumAttachmentRelationshipColumns.AttachmentImageMeta, opMap)...)
		}
	}

	if withCount >= 2 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}
	} else if withCount >= 0 {
		count, err = model.ForumAttachmentRelationships(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}
	}

	if pageSize > 0 && (withCount == -1 || withCount == 1) {
		if page > 1 {
			mods = append(mods, qm.Offset(pageSize*(page-1)))
		}
		mods = append(mods, qm.Limit(pageSize))
	}

	var columns []string
	if len(selectCol) > 0 {
		if selectCol == "," {
			columns = append(columns, model.ForumAttachmentRelationshipColumns.AttachmentRelationshipID)
		} else {
			columns = strings.Split(selectCol, ",")
		}
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.ForumAttachmentRelationships(mods...).All(ctx, r.mysqlConn)
	if err != nil {
		return
	}

	if withCount >= 2 {
		if limit > 0 && len(list) > limit {
			nextCount = 1
			list = list[:limit]
		}
		count = previousCount + nextCount*2
	}

	return
}
